<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>
        <input type="text" id="username">
    </p>
    <p>
        <input type="text" id="age">
    </p><p>
        <input type="button" value="提交" id="btn">
    </p>
    <script>
        var btn = document.querySelector('#btn');
        var username = document.querySelector('#username');
        var age = document.querySelector('#age');
        btn.onclick = function(){
            //创建Ajax对象
            var xhr = new XMLHttpRequest();
            var nameValue = username.value;
            var ageValue = age.value;
            //拼接请求参数
            var params = 'username=' + nameValue + '&age=' + ageValue;
            // alert(nameValue);
            // alert(ageValue);
            //设置请求方式和请求地址
            xhr.open('post','http://localhost:3000/post');
            //设置请求参数格式的类型（post请求必须设置）
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            //发送
            xhr.send(params);
            //获取服务器返回的数据
            xhr.onload = function(){
                console.log(xhr.responseText);
            }
        }
    </script>
</body>

</html>